`

Running Code Only If a Command Succeeds

We can even test the exit code of commands to determine if they were

successful or not, in this way:

if command; then

# command was successful

fi

if ! command; then

# command was unsuccessful

fi

Listing 2-6

Testing the exit code of a command

Youll often find yourself using this technique in bash, as commands aren’t

guaranteed to succeed. Failures could happen for reasons such as these:

A lack of the necessary permissions when creating resources

An attempt to execute a command that is not available on the operating

system

The disk being full when downloading a file

The network being down while executing network utilities

To see how this technique works, execute the following in your terminal:

$ if touch test123; then

echo "OK: file created"

fi

OK: file created

We attempt to create a file. Because the file creation succeeds, we print a

message to indicate this.

Using elif

If the first if condition fails, you can check for other conditions by using the

elif keyword (short for else if). To show how this works, lets write a program

that checks the arguments passed to it on the command line. The script in Listing

2-7 will output a message clarifying whether the argument is a file or a directory.

#!/bin/bash

USER_INPUT="${1}"

1 if [[ -z "${USER_INPUT}" ]]; then

echo you must provide an argument!

exit 1

fi

2 if [[ -f "${USER_INPUT}" ]]; then

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks